"""
Debug script to understand BUFR structure
"""

using PyCall

filename = "/home/docker/comgsi/tutorial/case_data/2018081212/obs/gdas1.t12z.1bamua.tm00.bufr_d"

py"""
from pybufrkit.decoder import Decoder
from pybufrkit.commands import generate_bufr_message
from pybufrkit.descriptors import ElementDescriptor

def decode_radiance_bufr_debug(filename, max_obs=5):
    '''Decode radiance BUFR file into observations.'''
    with open(filename, 'rb') as fh:
        data = fh.read()

    decoder = Decoder()
    observations = []

    for msg in generate_bufr_message(decoder, data, file_path=filename):
        try:
            msg.wire()
        except Exception:
            continue

        # Skip table definition messages
        if msg.n_subsets.value <= 1:
            continue

        desc_sets = getattr(msg.template_data.value, 'decoded_descriptors_all_subsets', [])
        val_sets = getattr(msg.template_data.value, 'decoded_values_all_subsets', [])

        # Process each subset
        for descs, vals in zip(desc_sets, val_sets):
            obs = {
                'channels': [],
                'brightness_temps': []
            }

            for desc, val in zip(descs, vals):
                if not isinstance(desc, ElementDescriptor):
                    continue

                try:
                    info = desc.as_list()
                    label = info[1][:30].strip()
                except Exception:
                    continue

                # Extract relevant fields
                if 'LATITUDE' in label.upper():
                    obs['latitude'] = float(val) if val is not None else None
                elif 'LONGITUDE' in label.upper():
                    obs['longitude'] = float(val) if val is not None else None
                elif 'SATELLITE ZENITH ANGL' in label.upper():
                    obs['zenith_angle'] = float(val) if val is not None else 0.0
                elif 'CHANNEL NUMBER' in label.upper():
                    obs['channels'].append(int(val) if val is not None else 0)
                elif 'BRIGHTNESS TEMPERATUR' in label.upper():
                    obs['brightness_temps'].append(float(val) if val is not None else 0.0)

            # Debug print
            print(f"Observation {len(observations)+1}:")
            print(f"  Lat/Lon: {obs.get('latitude')}, {obs.get('longitude')}")
            print(f"  Zenith: {obs.get('zenith_angle')}")
            print(f"  Channels: {len(obs['channels'])}")
            print(f"  Brightness temps: {len(obs['brightness_temps'])}")
            if len(obs['channels']) > 0:
                print(f"  First 3 channels: {obs['channels'][:3]}")
                print(f"  First 3 TB: {obs['brightness_temps'][:3]}")

            observations.append(obs)
            if len(observations) >= max_obs:
                return observations

    return observations
"""

decode_function = py"decode_radiance_bufr_debug"
obs_py = pycall(decode_function, PyAny, filename, 5)

println("\nDecoded $(length(obs_py)) observations")
